package com.llcbenwu.security;

import com.llcbenwu.filter.SmsCodeAuthenticationFilter;
import com.llcbenwu.provider.SmsCodeAuthenticationProvider;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 将自定义的过滤认证串联配置起来
 * @author lilinchun
 * @date 2021/10/29 0029 16:01
 */
@Component
public class SmsCodeSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {


    @Resource
    private AuthenticationFailureHandler llcAuthentiationFailHandler;

    @Resource
    private AuthenticationSuccessHandler llcAuthenticationSuccessHandler;

    @Resource
    private UserDetailsService userDetailsService;


    /**
     * 将自定义的过滤认证串联配置起来
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //实例化主键
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter=new SmsCodeAuthenticationFilter();
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        //设置成功和错误处理器
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(llcAuthentiationFailHandler);
        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(llcAuthenticationSuccessHandler);

        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider=new SmsCodeAuthenticationProvider();
         smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);

         http.authenticationProvider(smsCodeAuthenticationProvider) //这个方法就是将SmsCodeAuthenticationProvider告诉AuthenticationManager写入到它管理的provider中集合中
            .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);  //将我们之前写的那个过滤器加在了UsernamePasswordAuthenticationFilter之后
    }
}
